import Snake from "./Snake";
import Food from "./Food";
import ScorePanel from "./scorePanel";

class GameControl {
    snake:Snake
    food:Food
    scorePanel:ScorePanel
    // 创建一个属性来存储当前移动方向
    direction:string = ''
    // 记录游戏是否结束
    isLive:boolean = true
    constructor(){
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel()
        this.init()
    }
    // 游戏初始化
    init(){
        document.addEventListener('keydown',this.keydownHandler.bind(this))
        this.run()
    }
    // 键盘的点击处理函数
    keydownHandler(event:KeyboardEvent){
        this.direction = event.key
        console.log('key',event.key);   
    }
    // 控制蛇移动的方法
    run(){
        /**
         * 根据方向进行移动位置改变
         *      向上 top  减少
         *      乡下 top  增加
         *      向左    left    减少
         *      右边    left    增加
        */
       let X = this.snake.X
       let Y = this.snake.Y
       
       switch(this.direction){
           case 'ArrowUp':
           case 'Up' :
               Y -= 10
               this.snake.head.style.transform = 'rotateZ(360deg)'
               break
           case 'ArrowDown':
           case 'Down':
               Y += 10
               this.snake.head.style.transform = 'rotateZ(180deg)'
               break
           case 'ArrowLeft':
           case 'Left':
               X -= 10
               this.snake.head.style.transform = 'rotateZ(270deg)'
               break
           case 'ArrowRight':
           case 'Right':
               X += 10
               this.snake.head.style.transform = 'rotateZ(90deg)'
               break
       }
       this.checkFood(X,Y)
        //    修改蛇值-此处如果撞墙了 会抛出异常 需要进行捕获
        try {
            this.snake.X = X
            this.snake.Y = Y
        }catch(e:any) {
            // 虽然已经进行了捕获 但正式应为有捕获 所以程序并不会进行中止 所以应该更改当前游戏状态isLive
            this.isLive = false
            console.log('ssssssssssssss');
            
        }
        // 开启一个定时器
        this.isLive && setTimeout(this.run.bind(this),300 - (this.scorePanel.level - 1) * 30)
    }

    // 食物判断
    checkFood(x:number,y:number){
        // 表示吃到了食物
        if(x == this.food.X && y == this.food.Y){
            this.food.change()
            this.scorePanel.addScore()
            this.snake.addBody()
        }
    }
}

export default GameControl